﻿using System.CodeDom;
using System.ComponentModel;
using System.Configuration;
using System.Diagnostics;
using System.Dynamic;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices.Marshalling;
using System.Windows.Input;
using Wpf.SwitchTheme.Core;

namespace Wpf.SwitchTheme.ViewModels;

public class MainViewModel:INotifyPropertyChanged
{
    private ThemeManager _themeManager;
    private string _currentTheme=string.Empty;
    public MainViewModel()
    {
        _themeManager = new();
        _themeManager.RegisterTheme("LightColor", $@"ThemeColor\LightColor.xaml");
        _themeManager.RegisterTheme("DarkColor", $@"ThemeColor\DarkColor.xaml");
        _themeManager.ApplyTheme("LightColor");

        ThemeButtonState = new Dictionary<string, bool>()
        {
            { "LightColor", true }, { "DarkColor", false },
        };

        ChangeThemeCommand = new RelayCommand(themeName => ChangeTheme((string)themeName!));
        LoadTheme();
    }

    private void ChangeTheme(string? themeName)
    {
        _themeManager.ApplyTheme(themeName??string.Empty);
    }

    private void LoadTheme()
    {
        _currentTheme = ConfigurationManager.AppSettings["Current"]??"LightColor";
        UpdateThemeButtonState();
    }
    private void UpdateThemeButtonState()
    {
        foreach (var themeButtonKey in ThemeButtonState.Keys.ToList())
        {
            ThemeButtonState[themeButtonKey] = _currentTheme==themeButtonKey;
        }
    }

    private Dictionary<string,bool> _themeButtonState;

    public Dictionary<string,bool> ThemeButtonState
    {
        get { return _themeButtonState; }
        set { _themeButtonState = value; OnPropertyChanged();}
    }



    public ICommand ChangeThemeCommand { get; set; }


    public event PropertyChangedEventHandler? PropertyChanged;

    protected virtual void OnPropertyChanged([CallerMemberName] string? propertyName = null)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }

    protected bool SetField<T>(ref T field, T value, [CallerMemberName] string? propertyName = null)
    {
        if (EqualityComparer<T>.Default.Equals(field, value)) return false;
        field = value;
        OnPropertyChanged(propertyName);
        return true;
    }
}